package nconv.convert;

import nconv.utils.Pair;

import java.util.LinkedList;

/**
 * Created by lambert on 2016/4/29.
 */
public class ConvertContext {


	private static String pageName;

	private static String docName;

	private static String coreDocName;

	private static DOC_TYPE docType;

	private static String docTitle;

	private static LinkedList<Pair<String, String>> clauseStack =
			new LinkedList<>();


	public static String getPageName() {
		return pageName;
	}

	public static String getParentPageForPageClause(String clause, String pageName) {
		if (clauseStack.size() == 0 || clause == null) return null;

		for (Pair<String, String> pair : clauseStack) {
			if (clause.length() <= pair.first.length()) {
				continue;
			} else {
				if (pair.second.equals(pageName))  //not page clause
					return null;

				if (clause.startsWith(pair.first + ".")) {
					return pair.second;
				}
			}
		}
		return null;

	}

	public static void setPageInfo(String clause, String pageName) {
		ConvertContext.pageName = pageName;

		coreDocName = docName.substring(0, docName.indexOf('.'));
		if (DOC_TYPE.TGPP.equals(docType)) {
			int minusIdx = coreDocName.indexOf('-');
			if (minusIdx > 0) {
				coreDocName = coreDocName.substring(0, minusIdx);
			}
		}

		if (clause != null) {
			if (clauseStack.size() > 0 && clauseStack.peek().second.equals(pageName)) {
				return;
			}

			if (clauseStack.size() > 0){
				do {
					Pair<String, String> clausePage = clauseStack.peek();

					if (clause.startsWith(clausePage.first + ".")) {
						break;
					} else {
						clauseStack.pop();
					}
				} while (clauseStack.size() > 0);
			}
			clauseStack.push(new Pair<String, String>(clause, pageName));
		}

	}

	public static String getDocName() {
		return docName;
	}

	public static void setDocName(String docName) {
		ConvertContext.docName = docName;
		pageName = null;
	}

	public static DOC_TYPE getDocType() {
		return docType;
	}

	public static void setDocType(DOC_TYPE docType) {
		ConvertContext.docType = docType;
	}

	public static String getCoreDocName() {
		return coreDocName;
	}

	public static String getDocTitle() {
		return docTitle;
	}

	public static void setDocTitle(String docTtite) {
		ConvertContext.docTitle = docTtite;
	}

	public static enum DOC_TYPE{
		TGPP, FD, SYNC
	}
}
